package com.gitee.faster.redis.command;

import cn.hutool.core.map.CaseInsensitiveMap;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import lombok.Getter;

import java.util.Map;
import java.util.Objects;

/**
 * @author hongda.li
 */
@Getter
public final class CommandPool {

    private final Map<String, RedisCommand> commandMap = new CaseInsensitiveMap<>();

    public void add(final RedisCommand command) {
        this.commandMap.put(command.command().name(), command);
    }

    public void scan(Class<?> baseClass) {
        ClassUtil.scanPackage(ClassUtil.getPackage(baseClass), clz -> ClassUtil.isNormalClass(clz) && RedisCommand.class.isAssignableFrom(clz))
                .stream()
                .map(ReflectUtil::newInstanceIfPossible)
                .filter(Objects::nonNull)
                .map(RedisCommand.class::cast)
                .forEach(this::add);
    }

    public RedisCommand search(final String name) {
        return commandMap.get(name);
    }
}
